<!--  -->
<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-tag type="warning">
               <i class="el-icon-warning"></i>
                注意:只允许为第三级分类设置相关参数!
            </el-tag>

            <div class="goods_cascader">
               <span> 选择商品分类: </span>
                <el-cascader
                ref="cascader"
                size = "small"
                :options="categorysList"
                :props="defaultParams"
                v-model="selectKeys"
                @change = "handleChange"
                clearable
                change-on-select
                expand-trigger="hover">
                </el-cascader>
            </div>

             <el-tabs v-model="activeName" @tab-click="handleTab">
                 <!-- 动态参数 -->
                <el-tab-pane label="动态参数" name="many">
                     <el-button type="primary" size="small" :disabled="isBtnDisabled" @click="dialogVisible = true">添加参数</el-button>
                     <el-table :data="manyTableData" border stripe>
                         <!-- 展开行 -->
                         <el-table-column type="expand">
                             <template slot-scope="scope">
                                 <!-- <pre>{{scope.row}}</pre> -->
                                 <!-- 动态编辑标签 -->
                                 <el-tag
                                    :key="tag"
                                    v-for="tag in scope.row.attr_vals"
                                    closable
                                    :disable-transitions="false"
                                    @close="tagsClose(scope.row,tag)">
                                    {{tag}}
                                </el-tag>
                                    <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                        >
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                                    
                             </template>
                         </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                         <el-table-column
                            label="参数名称"
                            prop="attr_name"
                            >
                        </el-table-column>
                        <el-table-column
                            label="操作">
                            <template slot-scope="scope">
                                <!-- 编辑 -->
                                 <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
                                <!-- 删除按钮 -->
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delParams(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                     </el-table>
                </el-tab-pane>
                <!-- 静态属性 -->
                <el-tab-pane label="静态属性" name="only">
                      <el-button type="primary" size="small" :disabled="isBtnDisabled" @click="dialogVisible = true">添加属性</el-button>
                       <el-table :data="onlyTableData" border stripe>
                         <!-- 展开行 -->
                         <el-table-column type="expand">
                            <template slot-scope="scope">
                                 <!-- <pre>{{scope.row}}</pre> -->
                                 <!-- 动态编辑标签 -->
                                 <el-tag
                                    :key="tag"
                                    v-for="tag in scope.row.attr_vals"
                                    closable
                                    :disable-transitions="false"
                                    @close="tagsClose(scope.row,tag)">
                                    {{tag}}
                                </el-tag>
                                    <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                        >
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                                    
                             </template>
                         </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                         <el-table-column
                            label="属性名称"
                            prop="attr_name"
                            >
                        </el-table-column>
                        <el-table-column
                            label="操作">
                            <template slot-scope="scope">
                                <!-- 编辑 -->
                                 <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
                                <!-- 删除按钮 -->
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delParams(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                     </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加的对话框 -->
           <el-dialog
                :title="'添加' + titleText"
                :visible.sync="dialogVisible "
                width="30%"
                :before-close="closeUserDialog"
                @close = "addDialogClosed"
                >
                <el-form ref="addFormRef" :model="addForm" :rules="addFormRules">
                    <el-form-item :label="titleText" prop="attr_name">
                        <el-input  v-model = "addForm.attr_name" autocomplete="off" :label-width="formLabelWidth"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addParams">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 修改的对话框 -->
            <el-dialog
            :title="'修改' + titleText"
            :visible.sync="editDialog "
            width="30%"
            :before-close="closeEditDialog"
            >
            <el-form ref="editFormRef" :model="editForm" :rules="editFormRules">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input  v-model = "editForm.attr_name" autocomplete="off" :label-width="formLabelWidth"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialog = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
//这里存放数据
return {
    categorysList:[],
    defaultParams:{
        label:'cat_name',
        value:'cat_id',
        children:'children'
    },
    selectKeys:[],
    activeName: 'many',
    manyTableData:[],
    onlyTableData:[],
    dialogVisible:false,
    formLabelWidth:'120px',
    addForm:{},
    addFormRules:{
        attr_name:[
             { required: true, message: '请输入参数名称', trigger: 'blur' },
        ]
    },
    editDialog:false,
    editForm:{},
    editFormRules:{
        attr_name:[
             { required: true, message: '请输入参数名称', trigger: 'blur' },
        ]
    },
    inputVisible: false,
    inputValue: ''

 };
},
//监听属性 类似于data概念
computed: {
    isBtnDisabled(){
        if (this.selectKeys.length !== 3) {
            return true
        }else{
            return false
        }
    },
    // 选中的三级id
    cateId(){
        if (this.selectKeys.length == 3) {
            return this.selectKeys[2]
        }else{
            return null
        }
    },
    titleText(){
        if (this.activeName == "many") {
            return "动态参数"
        }else{
            return "静态属性"
        }
    },
   
    
},
//监控data中的数据变化
watch: {
    selectKeys(){
        if (this.$refs.cascader) {
            this.$refs.cascader.dropDownVisible = false
      }
    }
}, 
//方法集合
methods: {
     async getGoodsCategorys(){
        const {data} = await this.$http({
            url:"categories",
        })
        this.categorysList = data.data;
        
    },
    handleChange(){
        // console.log(this.selectKeys);
        this.getParamsData();   
    },
    handleTab(){
        // console.log(this.activeName)
        this.getParamsData();
    },
    async getParamsData(){
        if (this.selectKeys.length !== 3) {
            this.selectKeys = [];
            this.manyTableData = [];
            this.onlyTableData = [];
            return 
        }
            // 代表选择了三级分类,获取对应的数据
        const { data } = await this.$http({
            url:`categories/${this.cateId}/attributes`,
            params:{
                sel:this.activeName
            }
        })
        // console.log(this.selectKeys);
        // console.log(data.data);
        data.data.forEach(item => {
            item.attr_vals = item.attr_vals && item.attr_vals.split(" ") || [];
            // 控制文本框的显示和隐藏
            item.inputVisible = false;
            // 文本框中的值
            item.inputValue = ''
        })
        if (this.activeName == "many") {
            this.manyTableData = data.data
        }else{
            this.onlyTableData = data.data
        }
    },
    closeUserDialog(){
        this.$confirm('确认关闭？')
          .then(() => {
           this.dialogVisible = false;
          })
          .catch(()=>{})
    },
    addDialogClosed(){
        this.$refs.addFormRef.resetFields();
    },
    addParams(){
        this.$refs.addFormRef.validate(async vaild =>{
            if (!vaild) {
                return
            }

        const {data} = await this.$http.post(`categories/${this.cateId}/attributes`,{
            attr_name:this.addForm.attr_name,
            attr_sel:this.activeName,
        })
        if (data.meta.status !== 201) {
            return this.$message.error("添加参数失败!");
        }
            this.$message.success("添加参数成功!");
            this.getParamsData();
            this.dialogVisible = false;
        })
    },
    closeEditDialog(){
        this.$confirm('确认关闭？')
          .then(() => {
           this.dialogVisible = false;
          })
          .catch(()=>{})
    },
    async showEditDialog(scope){
        // console.log(id)
        // categories/:id/attributes/:attrId
        const { data } = await this.$http.get(`categories/${scope.cat_id}/attributes/${scope.attr_id}`,{
            params:{
                attr_sel:scope.attr_sel
            }
        });
        // console.log(data);
        this.editForm = data.data;
        this.editDialog = true;
    }, 
    // 操作中的编辑
    async editParams(){
        // categories/:id/attributes/:attrId
         const { data } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
            attr_name:this.editForm.attr_name,
            attr_sel:this.activeName
        });
      
        if (data.meta.status !== 200) {
            return this.$message.error("修改失败!");
        }
       
        this.$message.success("修改成功!");
        this.getParamsData();
        this.editDialog = false;
    },
    // 操作中的删除
    async delParams(scope){
        this.$confirm('您确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
       const { data } = await this.$http.delete(`categories/${scope.cat_id}/attributes/${scope.attr_id}`);
        // console.log(data);
        if (data.meta.status == 200) {
             this.$message({
             type: 'success',
             message: '已成功删除!'
          });
        }
          this.getParamsData();
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 关闭动态tag
    tagsClose(scope,tag){
        
         scope.attr_vals.splice(scope.attr_vals.indexOf(tag), 1);
    },
    async handleInputConfirm(scope) {
        if (scope.inputValue.trim().length ==0 ) {
             scope.inputValue = "",
             scope.inputVisible = false;
             return 
        }
        
        scope.attr_vals.push(scope.inputValue.trim());
        
        scope.inputVisible = false;
        scope.inputValue = '';
        const { data } = await this.$http.put(`categories/${this.cateId}/attributes/${scope.attr_id}`,{
            attr_name:scope.attr_name,
            attr_sel:scope.attr_sel,
            attr_vals:scope.attr_vals.join(" ")
        });
        console.log(data);
         if (data.meta.status !== 200) {
            return this.$message.error("添加失败!");
        }
        this.$message.success("添加成功!");
    },
    showInput(scope) {
        scope.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
},
//生命周期 - 创建完成（可以访问当前this实例）
created() {
    this.getGoodsCategorys();
},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {

},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.el-card{
    margin-top: 15px;
}
.el-tag{
    // width: 100%;
    margin-bottom: 15px;
    margin-right: 10px;
}
.goods_cascader{
    span{
        margin-right: 10px;
    }
}
.el-table{
    margin-top: 15px;
}
</style>